package zdz.kafkasequence;

import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.io.*;
import java.util.Properties;
import java.util.UUID;

public class Producer {
    public static String topic = "test1";//定义主题

    public static void main(String[] args) throws InterruptedException, FileNotFoundException {
        String FILE_DIR=args[0];

        Properties p = new Properties();
        p.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "niit-master:9092");//kafka地址，多个地址用逗号分割
        p.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        p.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<>(p);

        FileInputStream inputStream = new FileInputStream(FILE_DIR);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String str = null;

        try {
            bufferedReader.readLine();
            while (true) {
                if ((str = bufferedReader.readLine()) == null){
                    str = "null,null,null,null,null,null,QDU";
//                    Thread.sleep(1500);
                }
                ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic,
                        UUID.randomUUID().toString(),
                        str);

                kafkaProducer.send(record, new Callback() {
                    @Override
                    public void onCompletion(RecordMetadata metadata, Exception exception) {
                        System.out.println("offset=" + metadata.offset() +
                                            "partition" + metadata.partition());
                    }
                });
                System.out.println("消息发送成功:" + str);
                Thread.sleep(1500);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            kafkaProducer.close();
        }

    }
}
